package com.ikkong.qy.controller;

import java.io.ObjectOutputStream.PutField;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.ikkong.biz.model.Flow;
import com.ikkong.biz.model.FlowSegment;
import com.ikkong.biz.model.Parent;
import com.ikkong.biz.model.Student;
import com.ikkong.biz.model.Teacher;
import com.ikkong.biz.model.WeixinUser;
import com.ikkong.core.constant.Cst;
import com.ikkong.core.dao.Blade;
import com.ikkong.core.dao.Db;
import com.ikkong.core.jfinal.ext.kit.JStrKit;
import com.ikkong.core.jfinal.ext.shiro.ShiroKit;
import com.ikkong.qy.core.WeixinBaseController;
import com.ikkong.qy.util.CommonUtils;
import com.ikkong.qy.util.WeixinApi;
import com.ikkong.qy.util.WeixinInterface;
import com.ikkong.system.model.Attach;
import com.ikkong.system.model.Dept;
import com.jfinal.core.Controller;
import com.jfinal.upload.UploadFile;

public class WeixinFlowController extends WeixinBaseController {

	public void listReceived(){
		
		Integer userId = getUser().getId();
		int unreadCount = Db.init().queryInt(
				"select count(1) from tb_flow_segment fs where fs.operator_id = "+userId+" and fs.stat = 0", null);
		setAttr("count", unreadCount);
		List<Map> flowList = Db.init().queryListMap("select f.id,f.cname,f.title,f.ctime,f.is_end,fs1.stat,fs2.operator from tb_flow f,tb_flow_segment fs1,tb_flow_segment fs2 where f.seg_id = fs2.id and fs1.flow_id = f.id and fs1.operator_id = "+userId+" group by f.id");
		setAttr("flowList", flowList);
		render("/weixin/flow/list_received.html");
	}
	
	public void listSended(){		
		Integer userId = getUser().getId();
		int unreadCount = Db.init().queryInt(
				"select count(1) from tb_flow_segment fs where fs.operator_id = "+userId+" and fs.stat = 0", null);
		setAttr("count", unreadCount);
		List<Map> flowList = Db.init().queryListMap("select f.id, f.title,f.ctime,f.is_end,fs.stat,fs.operator from tb_flow f,tb_flow_segment fs where f.seg_id = fs.id and f.cuser = "+userId+" order by f.ctime desc");
		setAttr("flowList", flowList);
		render("/weixin/flow/list_sended.html");
	}
	
	public void start(){
		WeixinApi.createQyJsToken(this);
		List<Map> flowDeptList = flowDeptList();
		setAttr("nodeList", flowDeptList);
		List<Map> fileList = Db.init().queryListMap("select w.* from tb_wxfile w where w.user_mobile= "+getUser().getMobile()+" and w.status = 0 and DATEDIFF(w.ctime,now())>-3");
		setAttr("fileList", fileList);
		render("/weixin/flow/send.html");
	}
	
	public void view(){
		Integer flowId = getParaToInt();
		Flow flow = Blade.create(Flow.class).findById(flowId);
		List<FlowSegment> segmentList = Blade.create(FlowSegment.class).find("select * from tb_flow_segment fs where fs.flow_id = "+flowId+
				" order by fs.ctime asc", null);
		
		{
			List<Attach> attachList = Blade.create(Attach.class).find("select * from tfw_attach where find_in_set(id,'"+flow.getAttachUrl()+"')", null);
			flow.setAttachList(attachList);
		}
		
		for (int i = 0; i < segmentList.size(); i++) {
			FlowSegment seg = segmentList.get(i);
			String attaches = seg.getAttachUrl();
			if(!JStrKit.isBlank(attaches)){
				List<Attach> attachList = Blade.create(Attach.class).find("select * from tfw_attach where find_in_set(id,'"+attaches+"')", null);
				seg.setAttachList(attachList);
			}
		}
		
		
		setAttr("flow", flow);
		setAttr("segmentList", segmentList);
		setAttr("isOp", false);
		if(flow.getIs_end() == 0){
			FlowSegment seg = segmentList.get(segmentList.size()-1);
			if(seg.getStat() == 0 && seg.getOperator_id().intValue() == getUser().getId().intValue()){
				setAttr("isOp", true);
				WeixinApi.createQyJsToken(this);
				List<Map> flowDeptList = flowDeptList();
				setAttr("nodeList", flowDeptList);
				Integer userId = getUser().getId();
				List<Map> fileList = Db.init().queryListMap("select w.* from tb_wxfile w where w.user_mobile= "+getUser().getMobile()+" and w.status = 0 and DATEDIFF(w.ctime,now())>-3");
				setAttr("fileList", fileList);
			}
		}
		
		render("/weixin/flow/view.html");
	}
	
	public void doSend(){
		Attach fileAttach = null;
		Attach picAttach = null;
		
		
		UploadFile uploadFile = getFile();
		String serverId = getPara("serverId");
		
		if(!JStrKit.isBlank(serverId)){
			picAttach = WeixinInterface.downloadPic(serverId);
		}
		
		String wxFileIds = getPara("wxFileId","");
		
		if(uploadFile != null){
			System.out.println(uploadFile.getFileName());
			fileAttach = new Attach();
			fileAttach.setCreater(1);
			fileAttach.setCreatetime(new Date());

			fileAttach.setName(uploadFile.getFileName());
			fileAttach.setStatus(1);
			fileAttach.setUrl("/upload/" +uploadFile.getFileName());
			int id = Blade.create(Attach.class).saveRtId(fileAttach);
			fileAttach.setId(id);
		}
		
		String targetId = getPara("targetId");
		String title = getPara("title");
		String content = getPara("content");
		
		Teacher teacher = Blade.create(Teacher.class).findById(targetId);
		
		FlowSegment segment = new FlowSegment();
		segment.setOperator_id(teacher.getId());
		segment.setOperator(teacher.getName());
		segment.setStat(0);
		segment.setCtime(new Date());
		
		Integer segmentId = Blade.create(FlowSegment.class).saveRtId(segment);
		segment.setId(segmentId);
		
		Flow flow = new Flow();
		flow.setCtime(new Date());
		WeixinUser user = getUser();
		flow.setCname(user.getName());
		flow.setCuser(user.getId());
		flow.setTitle(title);
		flow.setDes(content);
		flow.setSeg_id(segmentId);
		flow.setIs_end(0);
		String attaches = wxFileIds;
		if(fileAttach != null){
			attaches = attaches+fileAttach.getId()+",";
		}
		if(picAttach != null){
			attaches = attaches+picAttach.getId();
		}
		flow.setAttachUrl(attaches);
		
		int flowId = Blade.create(Flow.class).saveRtId(flow);
		segment.setFlow_id(flowId);
		
		Blade.create(FlowSegment.class).update(segment);
		
		WeixinApi.pushFlow(flow, null, segment);
		redirect("/weixinFlow/listReceived");
	}
	
	public void doOp(){
		Attach fileAttach = null;
		Attach picAttach = null;
		
		
		UploadFile uploadFile = getFile();
		String serverId = getPara("serverId");
		
		if(!JStrKit.isBlank(serverId)){
			picAttach = WeixinInterface.downloadPic(serverId);
		}
		
		if(uploadFile != null){
			System.out.println(uploadFile.getFileName());
			fileAttach = new Attach();
			fileAttach.setCreater(1);
			fileAttach.setCreatetime(new Date());

			fileAttach.setName(uploadFile.getFileName());
			fileAttach.setStatus(1);
			fileAttach.setUrl("/upload/" +uploadFile.getFileName());
			int id = Blade.create(Attach.class).saveRtId(fileAttach);
			fileAttach.setId(id);
		}
		
		Integer segId = getParaToInt("segId");
		String comment = getPara("comment");
		
		FlowSegment segment =Blade.create(FlowSegment.class).findById(segId);
		segment.setComment(comment);
		segment.setStat(1);

		String attaches = getPara("wxFileId","");
		if(fileAttach != null){
			attaches = attaches+fileAttach.getId()+",";
		}
		if(picAttach != null){
			attaches = attaches+picAttach.getId();
		}
		segment.setAttachUrl(attaches);
		
		Blade.create(FlowSegment.class).update(segment);
		
		Integer flowId = getParaToInt("flowId");
		Flow flow = Blade.create(Flow.class).findById(flowId);
		String targetId = getPara("targetId");
		FlowSegment newSegment = null;
		if(JStrKit.isBlank(targetId)){
			//结束流程
			flow.setIs_end(1);
			Blade.create(Flow.class).update(flow);
			
		}else{
			//指定下一协办人
			Teacher teacher = Blade.create(Teacher.class).findById(targetId);
			
			newSegment = new FlowSegment();
			newSegment.setOperator_id(teacher.getId());
			newSegment.setOperator(teacher.getName());
			newSegment.setFlow_id(flowId);
			newSegment.setStat(0);
			newSegment.setCtime(new Date());
			
			int newSegId = Blade.create(FlowSegment.class).saveRtId(newSegment);
			
			flow.setSeg_id(newSegId);
			Blade.create(Flow.class).update(flow);
		}

		WeixinApi.pushFlow(flow, segment, newSegment);
		
		setAttr("title", "处理成功");
		setAttr("url",Cst.me().getBasePath()+"/weixinFlow/listReceived");
		render("/weixin/flow/result.html");
	}
	
	public void fileList(){
		Integer userId = getUser().getId();
		List<Map> fileList = Db.init().queryListMap("select w.id, w.name, w.ctime from tb_wxfile w where w.user_id = "+userId+" and w.status = 0 and DATEDIFF(w.ctime,now())>-3");
		setAttr("fileList", fileList);
		render("/weixin/flow/fileList.html");
	}
	
	private List<Map> flowDeptList(){
		List<Map> teacherDeptList = Db
				.init()
				.queryListMap(
						"select d.id,d.fullname as name,d.pid,'d1' as type from tfw_dept d where d.type = 1 order by d.num asc,d.id asc");
		List<Map> teacherList = Db
				.init()
				.queryListMap(
						"select t1.id,t1.name,t1.depts as pid,'t' as type from tb_teacher t1");

		List<Map> resList = new ArrayList<>();
		resList.addAll(teacherDeptList);
		resList.addAll(teacherList);

		return resList;
	}
	
}
